package plantshop.controller;

import java.io.Serializable;

import plantshop.controller.moves.Move;
import plantshop.controller.moves.MoveQueue;
import plantshop.model.Game;
import plantshop.view.ScoreScreen;
import plantshop.view.View;

public class Controller extends Thread implements Serializable{
	private static final long serialVersionUID = 6740682018352233154L;
	private static final int REPAINT = 20;
	private MoveQueue moveQueue;
	private Game game;
	private View view;
	private long time;
	
	public Controller(Game game, View view){
		moveQueue = new MoveQueue();
		this.game = game;
		this.view = view;
	}
	
	@Override
	public void run() {
		MoveQueue gameMoves = new MoveQueue();
		MoveQueue viewMoves = new MoveQueue();
		time = System.currentTimeMillis();
		long currTime;
		
		while(game.isRunning()){
			if(game.getGameTime()<=0){
				game.endGame();
				view.frame.getContentPane().removeAll();
				ScoreScreen scores = new ScoreScreen(view.getImages(),view.frame, game, view.getPlayer(), view.getAnimations());
				view.frame.getContentPane().add(scores);
				scores.frame.validate();
			}
			else{
				if(!moveQueue.isEmpty()){
					for(Move move:moveQueue){
						if(move!=null)
							move.execute(game);
					}
					moveQueue.reset();
				}
				else{
					gameMoves.addAll(game.getNextMoves());
					if(gameMoves.size() > 0){
						moveQueue.addAll(gameMoves);
						gameMoves.reset();
					}
				
					viewMoves.addAll(view.getNextMoves());
					if(viewMoves.size() > 0){
						moveQueue.addAll(viewMoves);
						viewMoves.reset();
					}
				}
				currTime = System.currentTimeMillis();
				if(currTime-time > REPAINT){
					update();
					time = currTime;
				}
			}
		}
	}
	
	private void update(){
		view.repaint();
	}
	
}
